/**
 Copyright (c) 2020-2022 宁波哥爱帮科技有限公司
 */
package cn.grab.fispservice.authentication.Interceptor;

import static com.fontana.base.object.TokenData.REQUEST_ATTRIBUTE_NAME;

import cn.grab.fispservice.util.ThreadLocalUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fontana.base.object.TokenData;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.yaml.snakeyaml.events.Event.ID;

/**
 * @description 用户认证拦截器
 * @author 16411
 * @date 2022/12/19 13:52
 */
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {

    //获取从请求头中携带的信息
    String header = request.getHeader(REQUEST_ATTRIBUTE_NAME);

    //json字符串转换成tokenData信息
    TokenData tokenData = JSON.parseObject(header, TokenData.class);

    //获取token中的userid,存储到threadLocal中
     Long userId = tokenData.getUserId();
   // Long userId = 45664654L;
    if (null != userId ) {

      ThreadLocalUtils.set(userId);
      //能正确存储,路由到下游
      return super.preHandle(request, response, handler);
    }

    //用户id为空,拦截请求
    return false;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {

    //请求处理完拦截,释放内存,避免内存泄漏
    ThreadLocalUtils.remove();

    super.postHandle(request, response, handler, modelAndView);
  }
}
